<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/28
 * Time: 15:41
 */

namespace App\Services;

use App\Lib\Util\QueryPager;
use App\Notes;
use Illuminate\Support\Facades\DB;

class NotesService
{
    public function baseQuery()
    {
        $query = Notes::where();
    }

    public function getNotesList($uid)
    {
        $field = [
            'notes.create_time AS date',
            'notes.content AS content',
            'notes.id AS id',
            'nu.is_read AS is_read',
            'ug.name AS admin',
        ];
        $str   = implode(',', $field);
        $info  = Notes::select(DB::raw($str))
            ->join('notes_users AS nu', function ($join) {
                $join->on('notes.id', '=', 'nu.notes_id');
            })
            ->join('users AS u', function ($join) {
                $join->on('u.id', '=', 'nu.user_id');
            })
            ->join('user_groups AS ug', function ($join) {
                $join->on('notes.user_groups_id', '=', 'ug.id');
            })
            ->where('u.id', '=', $uid)
            ->orderBy('nu.is_read', 'asc')
            ->orderBy('notes.create_time', 'desc')
            ->orderBy('nu.read_time', 'desc')
            ->get()
            ->toArray();
        return $info;
    }

    public function getNotesDetail($id, $uid)
    {
        $field = [
            'notes.content AS content',
            'notes.id AS id',
            'ug.name AS admin',
            'nu.id',
            'nu.is_read',
            'notes.create_time AS date'
        ];
        $str   = implode(',', $field);
        $info  = Notes::select(DB::raw($str))
            ->join('notes_users AS nu', function ($join) {
                $join->on('notes.id', '=', 'nu.notes_id');
            })
            ->join('users AS u', function ($join) {
                $join->on('u.id', '=', 'nu.user_id');
            })
            ->join('user_groups AS ug', function ($join) {
                $join->on('notes.user_groups_id', '=', 'ug.id');
            })
            ->where('u.id', '=', $uid)
            ->where('nu.notes_id', '=', $id)
            ->get()
            ->toArray();
        date_default_timezone_set("Asia/Shanghai");
        if ($info[0]['is_read'] != 1) {
            DB::table('notes_users')
                ->where('id', '=', $info[0]['id'])
                ->update(['is_read' => 1, 'read_time' => date('Y-m-d H:i')]);
        }
        return $info;
    }
}